#include <iostream>
#include <vector>
#include <queue>
#include <list>

using namespace std;
class Graph {
    int V;
    list<int> *adj;
public:
    Graph(int V); 
    void addEdge(int v, int w);
    void topologicalSort(); 
};
Graph::Graph(int V) {
    this->V = V;
    adj = new list<int>[V];
}
void Graph::addEdge(int v, int w) {
    adj[v].push_back(w); 
}


void Graph::topologicalSort() {
    int in_degree[V]; 
    vector<int> topo_order; 
    for (int i = 0; i < V; i++)
        in_degree[i] = 0;
    for (int v = 0; v < V; v++) {
        list<int>::iterator i;
        for (i = adj[v].begin(); i != adj[v].end(); ++i)
            in_degree[*i]++;
    }
    queue<int> q;
    for (int i = 0; i < V; i++)
        if (in_degree[i] == 0)
            q.push(i);
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        topo_order.push_back(u); 
        list<int>::iterator i;
        for (i = adj[u].begin(); i != adj[u].end(); ++i) {
            in_degree[*i]--;
            if (in_degree[*i] == 0)
                q.push(*i); 
        }
    }
    for (int i = 0; i < V; i++)
        if (in_degree[i] != 0) {
            cout << "图中存在环，无法进行拓扑排序。" << endl;
            return;
        }
    cout << "拓扑排序结果: ";
    for (int i = 0; i < topo_order.size(); i++)
        cout << topo_order[i] << " ";
    cout << endl;
}


int main() {
    Graph g(6);
    g.addEdge(5, 2);
    g.addEdge(5, 0);
    g.addEdge(4, 0);
    g.addEdge(4, 1);
    g.addEdge(2, 3);
    g.addEdge(3, 1);
    g.topologicalSort();
    return 0;
}